﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace DataAccessLibrary
{
    public class DataBase
    {
        public bool BackupData(string path)
        {

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            //Connect to DB
            var con = ConfigurationManager.AppSettings["ConnectionString"];
            var connect = new SqlConnection(con);
            connect.Open();
            //----------------------------------------------------------------------------------------------------
            var time = DateTime.Now;
            var date = time.ToString("yyyyMMddHHmmss");
            //Execute SQL---------------
            var command =
                new SqlCommand("backup database BlueM to disk ='" + path + date + "' with init,stats=10",
                               connect);
            command.ExecuteNonQuery();
            //-------------------------------------------------------------------------------------------------------------------------------
            connect.Close();
            return true;
        }

        public bool RestoreData(string path)
        {
            if (!File.Exists(path))
                return false;

            try
            {
                var con = ConfigurationManager.AppSettings["ConnectionString"];
                var connect = new SqlConnection(con);
                connect.Open();
                //-----------------------------------------------------------------------------------------

                //Excute SQL----------------
                var command = new SqlCommand("use master", connect);
                command.ExecuteNonQuery();
                command = new SqlCommand("restore database BlueM from disk = " + path, connect);
                command.ExecuteNonQuery();
                //--------------------------------------------------------------------------------------------------------
                connect.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public List<string> DataList(string path)
        {
            var ls = Directory.GetFiles(path);
            var dList = new List<string>();
            foreach (var s in ls)
            {
                DateTime dateTime;
                if (DateTime.TryParseExact(s, "yyyyMMddHHmmss", CultureInfo.InvariantCulture,
                                                       DateTimeStyles.None, out dateTime))
                {
                    dList.Add(s);
                }
            }
            return dList;
        }
    }
}
